package operation_system.producer_consumer;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//分别在lock的两个条件上进行细粒度的控制，防止唤醒不需要唤醒的线程
public class BMethod {
    public static void main(String[] args) {
        BStorage storage = new BStorage(new LinkedList<>());
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                while (true) {
                    try {
                        Thread.sleep(2000);
                        storage.produce();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }
        for (int i = 0; i < 1; i++) {
            new Thread(()->{
                while (true) {
                    try {
                        Thread.sleep(2000);
                        storage.consume();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }
    }
}
class BStorage{
    // 仓库最大存储量
    private final int MAX_SIZE = 10;
    // 仓库存储的载体
    private LinkedList<Object> list;
    // 锁
    private final Lock lock = new ReentrantLock();
    // 仓库满的条件变量
    private final Condition full = lock.newCondition();
    // 仓库空的条件变量
    private final Condition empty = lock.newCondition();

    public BStorage(LinkedList<Object> list) {
        this.list = list;
    }

    public void produce(){
        try{
            lock.lock();
            while (list.size() + 1 > MAX_SIZE) {
                try {
                    System.out.printf("生产者：%s，仓库已满！\n", Thread.currentThread().getName());
                    full.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(new Object());
            System.out.println("生产者：" + Thread.currentThread().getName() + "生产了一件！");
            empty.signalAll();

        }finally {
            lock.unlock();
        }
    }

    public void consume(){
        try{
            lock.lock();
            while (list.size() == 0) {
                System.out.printf("消费者：%s，仓库为空！\n", Thread.currentThread().getName());
                try {
                    empty.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("消费者:" + Thread.currentThread().getName() + "消费了一件！");
            list.remove();
            full.signalAll();


        }finally {
            lock.unlock();
        }
    }


}
